package cn.mumzone.pos.util;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RadioGroup;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

import cn.mumzone.basic.dialog.AlertDialog;
import cn.mumzone.basic.mvp.AbsPresenter;
import cn.mumzone.basic.util.EditTextUtil;
import cn.mumzone.basic.util.NetUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.basic.util.log.Elog;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.dialog.PosAlertDialog;
import cn.mumzone.pos.dialog.PosDialog;
import cn.mumzone.pos.event.BindMemberEntity;
import cn.mumzone.pos.model.LevelListEntity;
import cn.mumzone.pos.presenter.CashGoodsPresenter;
import cn.mumzone.pos.presenter.OpenOrderPresenter;
import cn.mumzone.pos.presenter.SettleAccountPresenter;
import cn.mumzone.pos.presenter.TimesCardPurchasePresenter;
import cn.mumzone.pos.ui.widgets.FlowLayout;
import cn.mumzone.pos.ui.widgets.keyboard.PosKeyBoardView;
import rx.functions.Action1;

/**
 * Created by JoeLjt on 2019/7/6.
 * Email: lijiateng1219@gmail.com
 * Description:
 * <p>
 * 用来为购物车添加或者绑定会员
 * <p>
 * {@link cn.mumzone.pos.ui.activity.ACT_OpenOrder},
 * {@link cn.mumzone.pos.ui.fragment.FRA_CashGoods} 两个类会用到，具体使用方法看注释
 */

public class AddMemberUtil {

    /**
     * 选择会员弹窗
     * 输入会员手机号搜索会员，传入 presenter 直接发起网络请求，通过 RxBus 进行成功回调
     *
     * @param context
     * @param presenter {@link OpenOrderPresenter} or {@link CashGoodsPresenter}
     */
    public static void showSelectMemberDialog(Context context, final Object presenter) {

        if (!NetUtil.isNetworkAvailable(context)) {
            PosToast.INSTANCE.makeShortToast(context, "网络不给力，请稍候再试");
            return;
        }

        AlertDialog selectMemberDialog = new PosDialog.PosBuilder(context)
                .setRealDialogContent(R.layout.dialog_select_member)
                .setDialogTitle("绑定会员")
                .setDialogNoConfirm()
                .setWidth(438)
                .show();
        PosKeyBoardView keyBoardView = selectMemberDialog.findViewById(R.id.keyboard_view);
        EditText etSelectPhone = selectMemberDialog.findViewById(R.id.et_phone);
        etSelectPhone.setFocusable(false);
        keyBoardView.attachTo(etSelectPhone);
        keyBoardView.setOnConfirmClickListener(new PosKeyBoardView.OnConfirmClickListener() {
            @Override
            public void onConfirmClick(String text) {
                if (presenter instanceof OpenOrderPresenter) {
                    ((OpenOrderPresenter) presenter).searchMember(text);
                } else if (presenter instanceof CashGoodsPresenter) {
                    ((CashGoodsPresenter) presenter).searchMember(text);
                } else if (presenter instanceof TimesCardPurchasePresenter) {
                    ((TimesCardPurchasePresenter) presenter).searchMember(text);
                } else if (presenter instanceof SettleAccountPresenter) {
                    ((SettleAccountPresenter) presenter).searchMember(text);
                }
            }
        });

        registerRxBus(selectMemberDialog);

    }

    /**
     * 添加会员弹窗，同上
     *
     * @param context
     * @param presenter {@link OpenOrderPresenter} or {@link CashGoodsPresenter}
     */
    private static void showAddMemberDialog(final Context context, final AbsPresenter presenter) {

        if (!NetUtil.isNetworkAvailable(context)) {
            PosToast.INSTANCE.makeShortToast(context, "网络不给力，请稍候再试");
            return;
        }

        final AlertDialog addMemberDialog = new PosDialog.PosBuilder(context, PosDialog.CONFIRM_TYPE_NORMAL)
                .setRealDialogContent(R.layout.dialog_add_member_new)
                .setDialogTitle("添加会员")
                .setSingleConfirmText("确定添加会员")
                .setWidth(445)
                .show();

        // 设置点击空白区域关闭键盘
        addMemberDialog.getWindow().getDecorView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getX() < 0 || event.getX() > 455) {
                    EditTextUtil.hideSoftInput(context, addMemberDialog.getView(R.id.et_phone));
                }
                return false;
            }
        });

        final EditText etPhone = addMemberDialog.getView(R.id.et_phone);
        final EditText etName = addMemberDialog.getView(R.id.et_name);
        final RadioGroup rgSex = addMemberDialog.getView(R.id.rg_sex);
        final FlowLayout<LevelListEntity> layoutGrade = addMemberDialog.getView(R.id.layout_member_level);

        List<LevelListEntity> levelList = JSON.parseArray(AppConstants.TEMP_MEMBER_LEVEL, LevelListEntity.class);
        String defaultLevel = "";
        for (int index = 0; index < levelList.size(); index++) {
            LevelListEntity level = levelList.get(index);
            if ("1".equals(level.getLevelType())) {
                defaultLevel = level.getFlowName();
                break;
            }
            if (index == levelList.size() - 1 && StringUtils.isEmpty(defaultLevel)) {
                defaultLevel = level.getFlowName();
                break;
            }
        }
        layoutGrade.checkDefault(defaultLevel);
        layoutGrade.update(levelList);
        addMemberDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                etName.clearFocus();
                etPhone.clearFocus();
                EditTextUtil.hideSoftInputMethod(context, etPhone);
                EditTextUtil.hideSoftInputMethod(context, etName);
            }
        });

        addMemberDialog.setOnClickListener(R.id.lb_confirm, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = etPhone.getText().toString().trim();
                String name = etName.getText().toString().trim();
                String sex = rgSex.getCheckedRadioButtonId() == -1 ? "" :
                        rgSex.getCheckedRadioButtonId() == R.id.rb_male ? "0" : "1";
                LevelListEntity checkedEntity = layoutGrade.getCheckedEntity();
                String level = checkedEntity == null ? "" : checkedEntity.getId();

                if (presenter instanceof OpenOrderPresenter) {
                    ((OpenOrderPresenter) presenter).doQuicklyAddMember(phone, name, sex, level);
                } else if (presenter instanceof CashGoodsPresenter) {
                    ((CashGoodsPresenter) presenter).doQuicklyAddMember(phone, name, sex, level);
                } else if (presenter instanceof SettleAccountPresenter) {
                    ((SettleAccountPresenter) presenter).doQuicklyAddMember(phone, name, sex, level);
                }

            }
        });

        registerRxBus(addMemberDialog);

    }

    /**
     * 绑定会员弹窗，同上
     *
     * @param context
     * @param listener 确定按钮的回调
     */
    private static void showUnbindMemberAlert(Context context, final DialogInterface.OnClickListener listener) {

        if (!NetUtil.isNetworkAvailable(context)) {
            PosToast.INSTANCE.makeShortToast(context, "网络不给力，请稍候再试");
            return;
        }

        new PosAlertDialog.Builder(context)
                .setRemindText("确认要解绑会员吗？")
                .setUseLoadingButton(true)
                .setPrimaryText("确认解绑")
                .setPrimaryLoadingText("解绑中")
                .setOnConfirmClickListener(new PosAlertDialog.OnConfirmClickListener() {
                    @Override
                    public void onConfirmClick(View view, Dialog dialog) {
                        if (listener != null) {
                            listener.onClick(dialog, -1);
                        }
                    }
                }).build().show();
    }

    /**
     * 通过传入的 {@param isMemberNull} 做判断
     * <p>
     * 添加会员
     *
     * @param context
     * @param isMemberNull
     * @param presenter        {@link OpenOrderPresenter} or {@link CashGoodsPresenter}
     * @param onUnbindListener
     * @see #showAddMemberDialog(Context, AbsPresenter)
     * <p>
     * 绑定会员
     * @see #showUnbindMemberAlert(Context, DialogInterface.OnClickListener)
     */
    public static void doSthAboutMemberBinding(Context context, boolean isMemberNull, AbsPresenter presenter,
                                               DialogInterface.OnClickListener onUnbindListener) {

        if (!NetUtil.isNetworkAvailable(context)) {
            PosToast.INSTANCE.makeShortToast(context, "网络不给力，请稍候再试");
            return;
        }

        if (isMemberNull) {
            // show add member dialog
            showAddMemberDialog(context, presenter);
        } else {
            // show unbind alert
            showUnbindMemberAlert(context, onUnbindListener);
        }
    }

    private static void registerRxBus(final AlertDialog dialog) {
        RxBus.getDefault().toObservable(BindMemberEntity.class)
                .subscribe(new Action1<BindMemberEntity>() {
                    @Override
                    public void call(BindMemberEntity settleSuccessEvent) {
                        onAddMemberSuccessful(dialog);
                    }
                });

    }

    /**
     * RxBus 的回调，监听 {@link BindMemberEntity} 的回调，关闭对应的弹窗
     *
     * @param dialog
     */
    private static void onAddMemberSuccessful(AlertDialog dialog) {
        dialog.dismiss();
    }

}
